// src/app/server.js
import fastify from 'fastify';
import dotenv from 'dotenv';
import { logger } from '../config/logger.js';

// 设置环境变量以支持 UTF-8 编码
process.env.NODE_OPTIONS = '--experimental-intl-locale';

// 加载环境变量
dotenv.config();

const app = fastify({ 
  logger: logger,
  // Ensure proper encoding
  charset: 'utf-8'
});

// 注册路由
import authRoutes from '../routes/auth.js';
import taskGroupRoutes from '../routes/taskGroup.js';
import taskRoutes from '../routes/task.js';
import taskLogRoutes from '../routes/taskLogRoutes.js';

app.register(authRoutes);
app.register(taskGroupRoutes);
app.register(taskRoutes);
app.register(taskLogRoutes);

// 注册认证中间件
import { authenticate } from '../middleware/auth.js';
app.decorate('authenticate', authenticate);

// 设置响应头确保UTF-8编码
app.addHook('onSend', async (request, reply) => {
  reply.header('Content-Type', 'application/json; charset=utf-8');
});

// 默认路由
app.get('/', async (request, reply) => {
  return { 
    message: '欢迎使用个人待办事项管理系统API', 
    version: '1.0.0' 
  };
});

// 启动服务器
const start = async () => {
  try {
    const port = process.env.PORT || 3000;
    await app.listen({ port, host: '0.0.0.0' });
    app.log.info(`服务器运行在 http://localhost:${port}`);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();